<template>
  <div class="card comment">
    <div class="card_title">
      <p class="card_title-name">评论 {{ count }}</p>
    </div>
    <yk-scrollbar ref="scrollbar" :height="height" style="padding: 0 24px">
      <yk-space dir="vertical">
        <reply
          v-for="item in comments"
          :key="item.id"
          :content="item"
          :isComment="true"
          @delete="deleteComment"
        />
      </yk-space>
    </yk-scrollbar>
    <div class="comment_pagination">
      <yk-pagination
        :total="count"
        size="m"
        @change="changePage"
      ></yk-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, getCurrentInstance } from "vue";
import reply from "./reply.vue";
import { comment } from "../../mock/data";
import type { CommentProps } from "./reply";

const proxy:any=getCurrentInstance()?.proxy

const props = withDefaults(defineProps<CommentProps>(), {
  pageSize: 8,
  height: "658px",
});

// 总数
const count = ref<number>(0);

// 数据内容
const comments = ref<any[]>([]); // 初始化为空数组

// 请求
type Request = {
  token?: string;
  pageSize: number; //单页条数
  nowPage: number; //当前页
};

const request: Request = {
  pageSize: props.pageSize,
  nowPage: 1,
};

// 获取数据
const drwCommentData = () => {
  try {
    // 确保 comment.data 存在
    if (!comment || !comment.data) {
      console.error("评论数据不存在");
      return;
    }

    let data = comment.data;
    count.value = data.count;

    // 确保 data.list 是数组
    if (Array.isArray(data.list)) {
      comments.value = data.list.slice(
        (request.nowPage - 1) * request.pageSize,
        request.nowPage * request.pageSize
      );
    } else {
      console.error("评论列表不是数组");
      comments.value = [];
    }
  } catch (error) {
    console.error("获取评论数据失败:", error);
    comments.value = [];
  }
};

// 翻页
const changePage = (e: number) => {
  request.nowPage = e;
  drwCommentData();
};

// 删除评论
const deleteComment = (e: number) => {
  comments.value = comments.value.filter((obj: any) => {
    return obj.id !== e;
  });
  proxy.$message({type:'primary',message:'删除成功'})
};

onMounted(() => {
  drwCommentData();
});
</script>

<style scoped lang="less">
.comment {
  position: relative;
  padding: @space-xl 0 64px;
  .card_title-name {
    padding: 0 @space-xl;
  }

  &_pagination {
    padding: @space-l @space-xl;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top: 1px solid @line-color-s;
    position: absolute;
    bottom: 0;
    width: 100%;
    left: 0;
  }
}
</style>
